package com.ljw.punishment.rulesengine;

import com.alibaba.fastjson.JSONObject;
import com.ljw.punishment.enginelistener.LogRuleEngineListener;
import com.ljw.punishment.enginelistener.LogRuleListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeasy.rules.api.RuleListener;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.api.RulesEngineListener;
import org.jeasy.rules.api.RulesEngineParameters;
import org.jeasy.rules.core.AbstractRulesEngine;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lijunwei
 * @date 2025/5/21
 */
@Slf4j
public class RuleEngineBuilder {

    private static final String LISTENER_CONFIG_SEPARATOR = ",";

    /**
     * 获取
     * @param typeCode
     * @return
     */
    public RulesEngine buildRuleEngine(String typeCode) {
        if (StringUtils.isBlank(typeCode)) {
            new Exception("构建引擎场景类型为空");
        }
        Map<String, RulesEngineListener> rulesEngineListeners = new HashMap<>();
        rulesEngineListeners.put("logRuleEngineListener", new LogRuleEngineListener());

        Map<String, RuleListener> ruleListenerMap=new  HashMap<>();
        ruleListenerMap.put("logRuleListener", new LogRuleListener());

//        System.out.println(JSONObject.toJSONString(ruleListenerMap));
//        ShopEngineConfigDAO shopEngineConfigDAO = shopEngineConfRepository.queryShopEngineByType(typeCode);
        String shopEngineConfigDAOstr = "{\"engineType\":0,\"firstAppliedSuccess\":0,\"firstExecError\":0," +
                "\"firstNotTrigger\":0,\"ruleEngineListener\":\"logRuleEngineListener\"," +
                "\"ruleListener\":\"logRuleListener\",\"sceneType\":\"check\"}";
        ShopEngineConfigDAO shopEngineConfigDAO = JSONObject.parseObject(shopEngineConfigDAOstr,
                ShopEngineConfigDAO.class);
        System.out.println(JSONObject.toJSONString(shopEngineConfigDAO));

        if (null == shopEngineConfigDAO) {
            new Exception("构建规则引擎场景类型为" + typeCode + "数据库未配置，请检查");
        }

        RulesEngineParameters engineParameters = convertToParameter(shopEngineConfigDAO);
        AbstractRulesEngine rulesEngine = RuleEngineSelector.select(shopEngineConfigDAO.getEngineType(),
                engineParameters);

        if (StringUtils.isNotBlank(shopEngineConfigDAO.getRuleEngineListener())) {
            String[] ruleEngineListenerStr = shopEngineConfigDAO.getRuleEngineListener().split(LISTENER_CONFIG_SEPARATOR);
            for (String s : ruleEngineListenerStr) {
                RulesEngineListener rulesEngineListener = rulesEngineListeners.get(s);
                if (null == rulesEngineListener) {
                    new Exception("引擎监听器注册名：" + s + "未找到");
                }
                rulesEngine.registerRulesEngineListener(rulesEngineListener);
            }
        }

        if (StringUtils.isNotBlank(shopEngineConfigDAO.getRuleListener())) {
            String[] ruleListenerStr = shopEngineConfigDAO.getRuleListener().split(LISTENER_CONFIG_SEPARATOR);
            for (String s : ruleListenerStr) {
                org.jeasy.rules.api.RuleListener ruleListener = ruleListenerMap.get(s);
                if (null == ruleListener) {
                    new Exception("规则监听器注册名：" + s + "未找到");
                }
                rulesEngine.registerRuleListener(ruleListener);
            }
        }
        log.info("场景code ：{}, 规则引擎构建完成,规则引擎 engine :{}", typeCode, JSONObject.toJSONString(rulesEngine));

        return rulesEngine;
    }


    private RulesEngineParameters convertToParameter(ShopEngineConfigDAO shopEngineConfigDAO) {

        RulesEngineParameters rulesEngineParameters = new RulesEngineParameters();

        if (null != shopEngineConfigDAO.getPriorityThreshold()) {
            rulesEngineParameters.setPriorityThreshold(shopEngineConfigDAO.getPriorityThreshold());
        }
        rulesEngineParameters.setSkipOnFirstAppliedRule(shopEngineConfigDAO.getFirstAppliedSuccess() == 1);
        rulesEngineParameters.setSkipOnFirstFailedRule(shopEngineConfigDAO.getFirstExecError() == 1);
        rulesEngineParameters.setSkipOnFirstNonTriggeredRule(shopEngineConfigDAO.getFirstNotTrigger() == 1);

        return rulesEngineParameters;
    }


}
